using System.Collections.Generic;
using System.Linq;
using cfg.config;
using cfg.game;
using Godot;
using kemocard.Components.List;
using kemocard.Scripts.Common;
using kemocard.Scripts.Module.Loading;
using kemocard.Scripts.Module.Run;
using kemocard.Scripts.MVC;
using kemocard.Scripts.MVC.View;

namespace kemocard.Scenes;

public partial class StorySlcView : BaseView
{
    [Export] private Button _confirm;
    [Export] private Button _cancel;
    [Export] private VirtualList _storyList;
    private string _id;

    public override void DoShow(params object[] args)
    {
        base.DoShow(args);
        _storyList.RenderHandler += StoryItemRender;
        _storyList.SelectedHandler += StoryItemSelect;
        _confirm.Pressed += ConfirmOnPressed;
        _cancel.Pressed += CancelOnPressed;
        List<object> data = [];
        if (StaticUtil.CheckSingleCond(new Dictionary<CondType, List<string>>
                { { CondType.GLOBALBOOL, ["HAS_TUTORIAL"] } }))
        {
            var ds = GameCore.Tables.TbStory.DataList;
            data.AddRange(ds.Where(storey => StaticUtil.CheckSingleCond(storey.Cond)));
        }
        else
        {
            data.Add("tutorial");
        }

        _storyList.SetData(data);
    }

    public override void DoClose(params object[] args)
    {
        _storyList.RenderHandler -= StoryItemRender;
        _storyList.SelectedHandler -= StoryItemSelect;
        _confirm.Pressed -= ConfirmOnPressed;
        _cancel.Pressed -= CancelOnPressed;
        base.DoClose(args);
    }

    private void StoryItemRender(Control arg1, int arg2, object arg3)
    {
        if (arg1 is not Components.StoryViewItem.StoryViewItem storyItem || arg3 is not string Id) return;
        var story = GameCore.Tables.TbStory.GetOrDefault(Id);
        if (story == null) return;
        storyItem.Data = story;
        storyItem.BorderRect.Visible = _id == storyItem.Data?.Id;
        storyItem.NameLab.Text = story.Name;
        storyItem.DescLab.Text = story.Desc;
    }

    private void StoryItemSelect(int arg1, int arg2)
    {
        _id = _storyList.GetCell<Components.StoryViewItem.StoryViewItem>(arg1)?.Data?.Id;
    }

    private void CancelOnPressed()
    {
        Close();
    }

    private void ConfirmOnPressed()
    {
        if (string.IsNullOrEmpty(_id)) return;
        var ctr = GameCore.ControllerMgr.GetModule<RunController>(ControllerType.Run);
        if (ctr.StartStory(_id))
        {
            // GameCore.ViewMgr.OpenView(ViewType.GameScene);
            var model = GameCore.ControllerMgr.GetControllerModel<LoadingModel>(ControllerType.Loading);
            model.SceneName = "GameScene";
            model.ViewType = ViewType.GameScene;
            GameCore.ViewMgr.CloseView(ViewType.MenuScene);
            GameCore.ControllerMgr.SendUpdate(ControllerType.Loading, CommonEvent.ShowLoadingScene, model);
        }

        Close();
    }
}